package com.dunqi.gpm.cangxi.home.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.webkit.WebView;

import com.dunqi.gpm.cangxi.R;
import com.dunqi.gpm.cangxi.common.api.ApiFactory;
import com.dunqi.gpm.cangxi.common.api.RxSchedulers;
import com.dunqi.gpm.cangxi.common.base.BaseFragment;
import com.dunqi.gpm.cangxi.common.util.SwipeUtil;
import com.dunqi.gpm.cangxi.common.util.WebUtil;
import com.dunqi.gpm.cangxi.home.bean.Project;
import com.dunqi.gpm.cangxi.home.constance.Constance;

import butterknife.BindView;
import io.reactivex.functions.Consumer;
import okhttp3.ResponseBody;

/**
 * Created by 空 on 2017/11/22 0022.
 */

public class ProjectDescriptionFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.web_view)
    WebView webView;
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;
    private Project project;

    @Override
    protected void refreshData(Bundle savedInstanceState) {
        net();
    }

    private void net() {
        ApiFactory.getInstance()
                .getProjectIntroduction(project.getProjectId())
                .compose(RxSchedulers.<ResponseBody>io_main())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {
                        SwipeUtil.loadCompleted(swipeRefresh);
                        String html = responseBody.string();
                        webView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        SwipeUtil.loadCompleted(swipeRefresh);
                    }
                });
    }

    @Override
    protected void initUiAndListener() {
        WebUtil.webSetting(webView, getActivity(), false);
        SwipeUtil.init(swipeRefresh);

        swipeRefresh.setOnRefreshListener(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_project_description;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        project = (Project) arguments.getSerializable(Constance.PROJECT);
    }

    public static ProjectDescriptionFragment newInstance(Project project) {
        ProjectDescriptionFragment projectDescriptionFragment = new ProjectDescriptionFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constance.PROJECT, project);
        projectDescriptionFragment.setArguments(bundle);
        return projectDescriptionFragment;
    }

    @Override
    public void onRefresh() {
        net();
    }
}
